<?php
declare (strict_types = 1);

namespace app\middleware;

class Validate
{
    /**
     * 处理请求,验证参数是否合法
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $validate=$request->pathinfo();
        if (!$validate){
            return $next($request);
        }

        if (strpos($validate, '/')) {
            // 支持场景
            list($validate, $scene) = explode('/', $validate);
        }

        $class='app\\validate\\'.ucfirst($validate);

        if (!class_exists($class)){
            return $next($request);
        }

        $v     = new $class();

        if (!empty($scene) && $v->hasScene($scene)) {
            $v->scene($scene);
            $result=$v->check($request->param());

            if (!$result){
                return json([
                    'code'=>2,
                    'data'=>'',
                    'msg'=>$v->getError()
                ]);
            }
        }

        return $next($request);
    }
}
